import React, { useContext, useEffect, useState } from 'react';
import { ActionList } from '@/api/modules/authentication';
import {
  Avatar,
  Divider,
  Empty,
  Input,
  Modal,
  Pagination,
  PaginationProps,
  Skeleton,
  Spin,
} from '@arco-design/web-react';
import debounce from 'lodash/debounce';
import styles from './style/index.module.less';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import { GlobalContext } from '@/context';
import cs from 'classnames';
import Row from '@arco-design/web-react/es/Grid/row';
import Col from '@arco-design/web-react/es/Grid/col';
import dayjs from 'dayjs';
import { LoginLogs } from '@/api/modules/entityProfiles';

const { Search } = Input;

interface Props {
  visible: boolean;
  setVisible: any;
}

function LoginHistory({ visible, setVisible }: Props) {
  const t = useLocale(locale);
  const { lang, rtl } = useContext(GlobalContext);
  const [skeletonLoading, setSkeletonLoading] = useState(false);
  const [spinLoading, setSpinLoading] = useState(false);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeCanChange: true,
    showTotal: true,
    total: 0,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });

  const [keywords, setKeywords] = useState('');
  const searchChange = debounce((value) => setKeywords(value), 500);

  useEffect(() => {
    if (visible) {
      setKeywords('');
      getActionList(false);
    }
  }, [visible]);

  useEffect(() => {
    visible && getActionList(true);
  }, [pagination.pageSize, pagination.current, keywords]);

  const [actionList, setActionList] = useState<Partial<any>[]>([]);
  const getActionList = async (spin) => {
    const { current, pageSize } = pagination;
    try {
      if (spin) setSpinLoading(true);
      else setSkeletonLoading(true);
      const { data } = await LoginLogs({
        pageNo: current,
        pageSize,
        q: keywords,
      });
      setActionList(data.data);
      setPatination({ ...pagination, total: data.count });
    } finally {
      if (spin) setSpinLoading(false);
      else setSkeletonLoading(false);
    }
  };

  const onChange = (pageNumber: number, pageSize: number) => {
    setPatination({
      ...pagination,
      current: pageNumber,
      pageSize,
    });
  };

  const cancel = () => {
    setVisible(false);
    setPatination({ ...pagination, current: 1, pageSize: 10 });
  };

  const title = (
    <div
      className={cs(
        styles['history-title'],
        rtl ? styles['history-title-rtl'] : ''
      )}
    >
      {t['history.title']}
    </div>
  );

  return (
    <Modal
      title={title}
      visible={visible}
      footer={null}
      style={{ width: 870 }}
      onCancel={cancel}
      className={cs(styles['history-action'])}
    >
      <Skeleton
        image
        text={{ rows: 15, width: ['100%'] }}
        loading={skeletonLoading}
      >
        <Search
          allowClear
          placeholder={t['history.search.placeholder']}
          onChange={searchChange}
          className={styles['history-action-search']}
        />

        {actionList.length == 0 ? (
          <div className={styles['history-empty']}>
            <Empty description={t['empty.noData']} />
          </div>
        ) : (
          <>
            <Spin loading={spinLoading} style={{ width: '100%' }}>
              <div className={styles['history-action-list']}>
                {actionList.map((item, index) => {
                  return (
                    <div key={index}>
                      <div className={styles['history-action-item']}>
                        <Avatar size={48}>
                          {item.officersVoo.officerName.slice(0, 1)}
                        </Avatar>
                        <Row style={{ flex: 1 }}>
                          <Col
                            span={14}
                            style={{ textAlign: rtl ? 'right' : 'left' }}
                          >
                            <span>
                              {t['history.name']}：
                              {lang === 'en-US'
                                ? item.officersVoo.officerName
                                : item.officersVoo.officerNameAr}
                              ( {t['history.email']}：{item.officersVoo.email})
                            </span>
                          </Col>
                          <Col
                            span={8}
                            style={{ textAlign: rtl ? 'right' : 'left' }}
                          >
                            <span>
                              {t['history.date']}：
                              {dayjs(item.createTime).format(
                                'YYYY-MM-DD HH:mm:ss'
                              )}
                            </span>
                          </Col>
                          <Col
                            span={24}
                            style={{
                              marginTop: '6px',
                              textAlign: rtl ? 'right' : 'left',
                            }}
                          >
                            <span style={{ display: 'flex' }}>
                              {t['history.entity']}：
                              <div
                                style={{ display: 'flex' }}
                                className={rtl ? 'rtl' : 'ltr'}
                              >
                                <div>
                                  {lang === 'en-US'
                                    ? item.officersVoo.entity?.name
                                    : item.officersVoo.entity?.nameAr}
                                  ,{t['ShareholdingPercentage']}
                                </div>
                                (
                                <div
                                  className={cs('ltr', rtl ? 'Cairo' : '')}
                                  style={{ display: 'flex' }}
                                >
                                  {
                                    item.officersVoo.entity
                                      ?.shareholdingPercentage
                                  }
                                  <div>%</div>
                                </div>
                                )
                              </div>
                              {/* {lang === 'en-US'
                                ? item.officersVoo.entity?.name
                                : item.officersVoo.entity?.nameAr}
                              , {t['ShareholdingPercentage']} (
                              {item.officersVoo.entity?.shareholdingPercentage}
                              %) */}
                            </span>
                          </Col>
                        </Row>
                      </div>
                      <Divider />
                    </div>
                  );
                })}
              </div>
            </Spin>
            <Pagination
              {...pagination}
              onChange={onChange}
              className={styles['history-action-pagination']}
            />
          </>
        )}
      </Skeleton>
    </Modal>
  );
}

export default LoginHistory;
